// import jQuery from "jquery";
import window from ".";
import { toJS } from "mobx";
import _ from "lodash";
import { WeaDialog, WeaTools } from 'ecCom';
import { spellResourceCondition } from '../components/excel-layout/cell-field/browser-element/Browser';
import formModeStores from '../stores';
import { Button } from 'antd';
import React from 'react';
import { observer } from 'mobx-react';
import ReactDOM from 'react-dom';
import jQuery from 'jquery';
import { modeForm_pc } from './excelUtil2';
import TableCell from '../components/excel-layout/TableCell';
import {importantParamRange} from './cubeUtil';

declare global {
    interface Window {
        getParentDialog;
        Card: any;
    }
}

jQuery.fn.extend({
    bindPropertyChange: function (funobj) {
        return this.each(function () {
            var thisid = jQuery(this).attr('id');
            window.ModeForm.addPropertyChangeFn(thisid, funobj);
        });
    }
});


export const modeForm = {
    dialogObj: undefined,
    __propertyChangeFnObj: {},
    __detailFieldChangeFnObj: {},
    /**
     * 获取当前的卡片的store
     */
    getCurrentModeStore: function () {
        let currentCardStore
        if (!window.location.href.includes('cube')) {
            let uuid = window.location.hash.slice(window.location.hash.lastIndexOf("=") + 1);
            currentCardStore = window.Card[uuid];
        }else if(window.location.href.includes('/cube/viewResource')|| formModeStores.cubeViewResource.visible){  
            /***
             * //针对资源面板里面的card页面，cardstore是单独的
             * 或者自定义页面配置了资源面板
             */
            currentCardStore = formModeStores.cubeViewResource.card;
        } else if(window.location.href.includes('/cube/viewCustomPage')){  //针对自定义页面里面的card页面，cardstore是单独的
            currentCardStore = formModeStores.customPageStore.card;
        }else{
            currentCardStore = formModeStores.Card;
            if (currentCardStore.isCardShow) {  //卡片页面扩展内嵌卡片
                currentCardStore = formModeStores.Card.card;
            }
        }
        return currentCardStore;
    },
    /**
    * 字段名称转换为字段id
    * @param symbol  主表/明细表标示，main/detail_1/detail_2，默认为main
    * @param prefix 是否需要field字符串前缀，默认为true
    */
    convertFieldNameToId: function (fieldname, symbol, prefix) {
        symbol = !!symbol ? symbol : "main";
        prefix = typeof prefix === "undefined" ? true : prefix;
        const { fieldNameMap } = this.getCurrentModeStore();
        const fieldKey = `${symbol}.${fieldname.toUpperCase()}`;
        let fieldid: any = "";
        if (fieldNameMap.has(fieldKey)) {
            fieldid = fieldNameMap.get(fieldKey);
            fieldid = prefix ? `field${fieldid}` : fieldid;
        }
        return fieldid;
    },
    /**
    * 获取字段值
    */
    getFieldValue: function (fieldMark) {
        const [fieldid, index] = fieldMark.split("_");
        let fieldProps = this.getFieldInfo(fieldid);
        if (fieldProps.isdetail) {
            const detailindex = fieldProps["detail"];
            return this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).values();
        } else {
            return this.getCurrentModeStore().cubeForm.$(fieldMark).values();
        }
    },
    /**
    * 获取字段值对象
    */
    getFieldValueObj: function (fieldMark) {
        const fieldObj = this.getFieldObj(fieldMark);
        return fieldObj === null ? {} : fieldObj;
    },
    getFieldObj: function (fieldMark) {
        if (fieldMark.indexOf("field") === -1)
            return null;
        const [fieldid, index] = fieldMark.split("_");
        let fieldProps = this.getFieldInfo(fieldid);
        if (fieldProps.isdetail) {
            const detailindex = fieldProps["detail"];
            const bindObj = this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).bind();
            return {
                value: bindObj.value,
                valueSpan: bindObj.valueSpan,
                specialobj: bindObj.valueObj
            }
        } else {
            const bindObj = this.getCurrentModeStore().cubeForm.$(fieldMark).bind();
            return {
                value: bindObj.value,
                valueSpan: bindObj.valueSpan,
                specialobj: bindObj.valueObj
            }
        }
    },
    /**
   * 修改字段值，适用范围(单行文本、多行文本、选择框、浏览框、check框(0/1))
   * @params valueInfo(JSON)    非浏览框格式为：valueObj ="修改后的值"，
   *   *                specialobj为浏览按 钮信息，数组格式;
   *                showhtml属性只在文本字段类型且只读情况下生效；
   */
    changeFieldValue: function (fieldMark, valueInfo,type="") {
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            let fieldProps = toJS(that.getFieldInfo(fieldid));
            const _cubeForm = this.getCurrentModeStore().cubeForm;
            if (!_.isEmpty(valueInfo)) {
                let valueObj: any;
                if (valueInfo.specialobj && _.isArray(valueInfo.specialobj)) {
                    valueObj = valueInfo.specialobj;
                } else {
                    valueObj = valueInfo.value;
                }
                let isEqualShowHtml = true;
                const oldShowhtml= _.get(this.getCurrentModeStore().allFields, fieldid).showhtml;
                if(oldShowhtml && valueInfo.showhtml){
                    isEqualShowHtml = oldShowhtml === valueInfo.showhtml;
                    if(!isEqualShowHtml){
                        _.set(this.getCurrentModeStore().allFields, `${fieldid}.showhtml`,valueInfo.showhtml);
                    }
                }else if(oldShowhtml || valueInfo.showhtml){
                    isEqualShowHtml = false
                    _.set(this.getCurrentModeStore().allFields, `${fieldid}.showhtml`,oldShowhtml?'':valueInfo.showhtml);
                }
                const newval = valueObj;
                let oldval = '';
                if (fieldProps.isdetail) {
                    const detailindex = fieldProps["detail"];
                    if (fieldProps && fieldProps.fieldhtmltype == 3) { //浏览按钮
                        oldval = toJS(_cubeForm.$(detailindex).$(index).$(fieldid).valueObj);
                    }else if(type == 'upload'){
                        _cubeForm.$(detailindex).$(index).$(fieldid).setUploadData({filedatas : valueInfo});
                        return;
                    }  else {
                        oldval = _cubeForm.$(detailindex).$(index).$(fieldid).values();
                    }
                    if (_.isEqual(oldval, newval) && isEqualShowHtml) { return; }
                    _cubeForm.setValue(`${detailindex}.${index}.${fieldid}`, valueObj);
                } else {
                    if (fieldProps && fieldProps.fieldhtmltype == 3) { //浏览按钮
                        oldval = toJS(_cubeForm.$(fieldMark).valueObj);
                    }else if(type == 'upload'){
                        _cubeForm.$(fieldMark).setUploadData({filedatas : valueInfo});
                        return;
                    } else {
                        oldval = _cubeForm.$(fieldMark).values();
                    }
                    if (_.isEqual(oldval, newval) && isEqualShowHtml) { return; }
                    _cubeForm.setValue(fieldMark, valueObj);
                }
            }
        } catch (e) {

        }
    },
    /**
   * 修改字段只读/可编辑/必填/隐藏属性/隐藏行，此接口优先级低于标准功能显示属性联动(即设置了显示属性联动的可能覆盖此设置)
   * @params viewAttr(int)  1：只读，2：可编辑，3：必填，4：隐藏字段标签及 内容,5:隐藏行，注意目前只有主表有隐藏行功能
   */
    changeFieldAttr: function (fieldMark, viewAttr) {
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            let fieldProps = that.getFieldInfo(fieldid);
            if (viewAttr == "1") {
                viewAttr = 3
            } else if (viewAttr == "2") {
                viewAttr = 1
            } else if (viewAttr == "3") {
                viewAttr = 2
            }
            if (fieldProps.isdetail) {
                const detailindex = fieldProps["detail"];
                this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).setViewAttrs("", viewAttr);
            } else {
                if (this.getCurrentModeStore().cubeForm.has(fieldid)) {
                    // 如果隐藏了行,修改为未隐藏行
                    this.getCurrentModeStore().cubeForm.$(fieldid).viewAttrs[""] == '5' && viewAttr != '5' &&
                        this.getCurrentModeStore().cubeForm.$(fieldid).hideOrShowTr(false);

                    this.getCurrentModeStore().cubeForm.$(fieldid).setViewAttrs("", viewAttr);
                }
            }
        } catch (e) {

        }
    },
    /**
     * 修改单个字段属性，修改值同时修改显示属性,这个方法目前不需要
     * @params valueInfo(obj) 可为空，变更的字段值
     */
    changeSingleField: function (fieldMark, valueObj, variableInfo) {
        if (valueObj) {
            this.changeFieldValue(fieldMark, valueObj);
        }
        if (variableInfo && variableInfo.viewAttr) {
            this.changeFieldAttr(fieldMark, variableInfo.viewAttr);
        }
    },
    /**
    * 批量修改多个字段值及属性
    * @params changeDatas(obj)  格式{field110:{value:"11"},field111_1:{value:"22"}
    * @params changeVariable(obj) 格式{field110:{viewAttr:1},field111_1:{viewAttr:3}}
    */
    changeMoreField: function (changeDatas = {}, changeVariable = {}) {
        const that = this;
        try {
            _.forEach(changeDatas, function (value, key) {
                return that.changeFieldValue(key, value);
            });
            _.forEach(changeVariable, function (value, key) {
                return that.changeFieldAttr(key, value["viewAttr"]);
            });
        } catch (e) {

        }
    },
    /**
     * 添加明细并赋值
     * @param fieldMark
     *
     */
    addDetailRow: function (detailMark, initialData = {}) {
        const that = this;
        try {
            const orderid = detailMark.split("_")[1];
            this.getCurrentModeStore().cubeForm.addRow(orderid);
            const len = this.getCurrentModeStore().cubeForm.$(detailMark).values().length - 1;
            if (!_.isEmpty(initialData)) {
                const detailData: any = {};
                _.forEach(initialData, (value, key) => {
                    if (_.isArray(value['value'])) {
                        detailData[key] = that.deal4ReplaceDatas(value['value'], key);
                    } else {
                        detailData[key] = value['value'];
                    }
                })
                this.getCurrentModeStore().cubeForm.updateValues({ [detailMark]: { [len]: detailData } }, {})
            }
        } catch (error) {

        }
    },
    /**
    * 删除明细行,没有提示删除的确认框(会清空明细已选情况)
    * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
    *
    */
    delDetailRow: function (detailMark, rowIndexMark) {
        try {
            if (this.getCurrentModeStore().cubeForm.has(detailMark)) {
                this.getCurrentModeStore().cubeForm.delDetailRow(detailMark, rowIndexMark);
            }
        } catch (error) {

        }
    },
    /**
    * 选中明细行
    * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
    * @params rowIndexMark(String) 明细行标示，全部选中:all,选中部分："0,1，2，3"
    * @params needClearBeforeChecked(Boolean) 是否需要清除已有选中，默认为false
    */
    checkDetailRow: function (detailMark: string, rowIndexMark: string, needClearBeforeChecked: boolean) {
        try {
            let obj: any = {};
            let valueArr = this.getCurrentModeStore().cubeForm.$(detailMark).values();
            if (rowIndexMark == "all") {
                valueArr && valueArr.length > 0 && valueArr.map((data, index) => {
                    obj = {
                        ...obj,
                        [index]: { ...data, checkbox: "1" }
                    }
                })
            } else {
                const rowIndexMarkArr = rowIndexMark.split(",");
                if (needClearBeforeChecked) {
                    valueArr = valueArr.map((data) => { return { ...data, checkbox: "0" } });
                }
                rowIndexMarkArr && rowIndexMarkArr.length > 0 && rowIndexMarkArr.map(data => {
                    obj = {
                        ...obj,
                        [data]: { ...valueArr[data], checkbox: "1" }
                    }
                })
            }
            this.getCurrentModeStore().cubeForm.updateValues({ [detailMark]: { ...valueArr, ...obj } })
        } catch (error) {

        }
    },
    /**
   * 获取明细所有行标示，逗号分隔
   * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
   */
    getDetailAllRowIndexStr: function (detailMark) {
        try {
            const indexArr = this.getCurrentModeStore().cubeForm.$(detailMark).map(d => d.key);
            return `${indexArr}`
        } catch (error) {

        }
    },
    /**
        * 根据字段id获取对应的明细行数据库key值
        */
    getDetailRowKey: function (fieldMark) {
        const that = this;
        try {
            if (fieldMark.indexOf("field") === -1 || fieldMark.indexOf("_") === -1)
                return -1;
            const [fieldid, index] = fieldMark.split("_");
            const fieldInfo = toJS(that.getFieldInfo(fieldid));
            let row;
            if (fieldInfo.isdetail) {
                const detailindex = fieldInfo["detail"];
                row = this.getCurrentModeStore().cubeForm.$(detailindex).$(index).values();
            }
            let id = row.dtl_id ? row.dtl_id : -1;
            return id;
        } catch (e) {
            return -2;
        }
    },
    /**
    * 控制明细点添加是否复制指定行记录(不复制附件上传字段)
    * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
    * @params needCopy(Boolean)  true需要复制，false取消复制
    */
    setDetailAddUseCopy: function (detailMark, needCopy) {
        const that = this;
        try {
            if (needCopy) {
                const initParams = _.last(this.getCurrentModeStore().cubeForm.$(detailMark).values())
                that.addDetailRow(detailMark, initParams);
            } else {
                that.addDetailRow(detailMark, {});
            }
        } catch (error) {

        }
    },
    /**
    * 浏览按钮请求数据接口，支持传输自定义参数，联想输入及弹窗都支持
    */
    appendBrowserDataUrlParam: function (fieldMark, jsonParam = {}) {
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            const fieldInfo = toJS(that.getFieldInfo(fieldid));
            const tempParams = this.getCurrentModeStore().allFields[fieldid].browserProps.dataParams || {};
            if (fieldInfo && fieldInfo.fieldhtmltype == 3) {
                if (fieldInfo.isdetail) {//明细表
                    const detailindex = fieldInfo["detail"];
                    const detailProps = this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid);
                    detailProps.dataParams = {
                        ...tempParams,
                        ...jsonParam
                    }
                } else {
                    this.getCurrentModeStore().cubeForm.$(fieldid).dataParams = {
                        ...tempParams,
                        ...jsonParam
                    }
                }
            }
        } catch (error) {

        }
    },
    /**
    * 获取浏览按钮字段对应的显示值
    */
    getBrowserShowName: function (fieldMark, splitChar = ",") {
        let showname: string = "";
        let showNameArr: any = [];
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            let fieldProps = that.getFieldInfo(fieldid);
            if (fieldProps.isdetail) {
                const detailindex = fieldProps["detail"];
                showNameArr = toJS(this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).valueObj);
            } else {
                showNameArr = toJS(this.getCurrentModeStore().cubeForm.$(fieldMark).valueObj);
            }
        } catch (e) {

        }
        const tempArr: any = [];
        showNameArr.map(item => {
            tempArr.push(item.name);
        })
        showname = tempArr.join(splitChar)
        return showname;
    },
    /**
    * 移除选择框字段选项  被移除之外其他选项可选
    */
    removeSelectOption: function (fieldMark, optionKeys) {
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            const fieldInfo = toJS(that.getFieldInfo(fieldid));
            let newOptions: any = fieldInfo.options;
            if (fieldInfo && fieldInfo.options) {
                optionKeys = optionKeys.split(",");
                optionKeys && optionKeys.length > 0 && optionKeys.map((key: string) => {
                    newOptions = newOptions.filter(d => d.key !== key + "");
                    newOptions = newOptions.filter(d => d.cancel != '1');
                })
            }
            if (fieldInfo.isdetail) {
                const detailindex = fieldInfo["detail"];
                this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).set('options', newOptions);
            } else {
                this.getCurrentModeStore().cubeForm.$(fieldid).set('options', newOptions);
            }
        } catch (error) {

        }
    },
    /**
        * 控制选择框字段选项范围   范围外选项隐藏
        * @params optionKeys(Arrsry) [1,2]
        */
    controlSelectOption: function (fieldMark: string, optionKey: string) {
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            const fieldInfo = toJS(that.getFieldInfo(fieldid));
            let newOptions: any = toJS(fieldInfo.options);
            const options: any = [];
            if (fieldInfo && fieldInfo.options) {
                const optionKeys = optionKey.split(",");
                optionKeys && optionKeys.length > 0 && optionKeys.map((key: string) => {
                    const temp: any = newOptions.filter(d => d.key == key + "" && d.cancel != '1')[0];
                    if (temp) {
                        options.push(temp);
                    }
                })
            }
            if (fieldInfo.isdetail) {
                const detailindex = fieldInfo["detail"];
                this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).set('options', options);
            } else {
                this.getCurrentModeStore().cubeForm.$(fieldid).set('options', options);
            }
        } catch (error) {

        }
    },
    /**
   * 控制表单按钮是否点击
   * @param flag : true 按钮全部置灰不可操作 false 恢复按钮可操作状态
   */
    controlBtnDisabled: function (isDisabled) {
        this.getCurrentModeStore().cardTab.disabled = isDisabled;
    },
    /**
     * 获取字段信息
     */
    getFieldInfo: function (fieldMark) {
        let mainFields = this.getCurrentModeStore().allFields;
        let fieldProps = formModeStores.Card.fieldsProps;
        try {
            const fieldid = fieldMark.split("_")[0];
            const fieldProp = { ...fieldProps[fieldid] };
            const { ismandatory, isedit } = fieldProp;
            const viewattr = ismandatory ? 3 : (isedit ? 2 : 1);
            return { ...mainFields[fieldid], viewattr: viewattr };
        } catch (e) {

        }
    },
    /**
    * 获取字段当前的字段属性
    */
    getFieldCurViewAttr: function (fieldMark: string) {
        try {
            const childrenFields = jQuery("*.fieldValue");//隐藏行内的field元素
            let fieldattr = "";
            if (childrenFields) {
                Array.prototype.forEach.call(childrenFields, element => {   //获取fieldid
                    const dataset = this.getDataset(element);
                    if (dataset.fieldmark == fieldMark) {
                        fieldattr = dataset.fieldattr;
                    }
                });
            }
            return fieldattr;
        } catch (e) {

        }
    },
    getDataset: function (ele) {
        if (ele.dataset) {
            return ele.dataset;
        } else {
            var attrs = ele.attributes,//元素的属性集合
                dataset = {}, name, matchStr;
            for (var i = 0; i < attrs.length; i++) { //是否是data- 开头
                matchStr = attrs[i].name.match(/^data-(.+)/);
                if (matchStr) { //data-auto-play 转成驼峰写法 autoPlay
                    name = matchStr[1].replace(/-([\da-z])/gi, function (all, letter) {
                        return letter.toUpperCase();
                    });
                    dataset[name] = attrs[i].value;
                }
            }
            return dataset;
        }
    },
    /***
     *
     */
    getCardUrlInfo: function () {
        try {
            let baseinfo = this.getCurrentModeStore().base;
            const baseParams = this.getCurrentModeStore().params;
            return { ...baseParams, ...baseinfo };
        } catch (e) {

        }
    },
    /***
     * 打开一个自定义对话框
     */
    openCustomDialog: function (prop, buttons?) {
        let newbuttons: any = new Array();
        var dia = this.dialogObj;
        for (let button of buttons) {
            newbuttons.push(<Button id={button.btnname} type='primary' onClick={(e) => {
                let methodname = button.callfun;
                if (methodname.indexOf('base.') >= 0) {
                    methodname = methodname.replace('base.', '');
                    eval(methodname + "()");
                } else {
                    eval('$(e.target).closest(".ant-modal-content").find("iframe")[0].contentWindow.' + methodname + "()");
                }
            }}>{button.btnname}</Button>);
        }
        if (dia == undefined) {
            let node = document.createElement('div');
            ReactDOM.render(
                <MyCustomDialog ref={(r) => dia = r} prop={prop} buttons={newbuttons} />, node
            );
            WeaTools.WindowFunc.getTop().document.body.appendChild(node);
            this.dialogObj = dia;
        } else {
            this.dialogObj.update(prop, newbuttons);
            this.dialogObj.show();
        }
        return dia;
    },
    /**
     * 关闭指定的自定义对话框
     */
    closeCustomDialog: function (callBack=()=>{}) {
        this.dialogObj.close(callBack);
    },
    /**
    * 添加明细行
    * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
    * @params initAddRowData(JSON) 新增行设置的初始值，可不传；格式为{field110:"111",field112:"22",...},注意key不带下划线标示
    */
    deal4ReplaceDatas: function (replaceDatas, fieldtype) {
        if (fieldtype == '141') {
            const props = replaceDatas.map(d => d.prop);
            return {
                value: spellResourceCondition(props),
                valueObj: props
            }
        } else {
            return {
                value: replaceDatas.map(d => d.id || d.randomFieldId).join(","),
                valueSpan: replaceDatas.map(d => d.name || d.lastname).join(","),
                valueObj: replaceDatas
            }
        }
    },
    /**
     * 文本字段可编辑状态，当值为空显示默认灰色提示信息，鼠标点击输入时消失
     */
    setTextFieldEmptyShowContent: function (fieldMark: string, showContent: string) {
        try {
            if (!fieldMark || fieldMark.indexOf("field") === -1)
                return;
            const fieldid = fieldMark.split("_")[0];
            const fieldInfo = toJS(this.getFieldInfo(fieldid));
            if (fieldInfo.isdetail) {
                // const detailindex = fieldInfo["detail"];
                // this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).$placeholder = showContent;
                this.getCurrentModeStore().controlDetailRowAttr(fieldMark, { emptyShowContent: showContent });
            } else {
                this.getCurrentModeStore().cubeForm.$(fieldid).$placeholder = showContent;
            }
        } catch (error) {

        }
    },
    /**
     * 复写浏览按钮属性
     */
    overrideBrowserProp: function (fieldMark: string, jsonParam = {}) {
        try {
            const [fieldid] = fieldMark.split("_");
            const fieldInfo = toJS(this.getFieldInfo(fieldid));
            if (fieldInfo && fieldInfo.fieldhtmltype == 3) {//限制浏览框类型
                this.getCurrentModeStore().controlBrowserProp(fieldMark, jsonParam);
            }
        } catch (error) {

        }
    },

    /**
     * 更新提交参数
     * @param {Object} updateInfo
     */
    updateSubmitInfo: function (updateInfo) {
    },
    /**
     * 获取submitParams 中的参数值
     * @param {Object} key
     */
    getSubmitInfoByKey: function (key) {
    },
    /**
     * 附件下载
     * @param {Object} downloadUrl
     */
    setFileDownload: function (downloadUrl) {
    },
    downLoadFile: function (fileid) { }
    ,
    changeReplyAttr: function () {

    },
    /**
    * 字段值变化绑定事件
    * @params fieldMark(String) 绑定字段标示串，明细字段带下划线标示
    */
    bindFieldChangeEvent: function (fieldMarkStr, funobj) {
        !!fieldMarkStr && fieldMarkStr.split(",").map(fieldMark => {
            this.addPropertyChangeFn(fieldMark, funobj);
        });
    },
    addPropertyChangeFn: function (key, funobj) {
        if (!key || key.indexOf("field") === -1)
            return;
        let fnArr = this.__propertyChangeFnObj[key];
        if (!!!fnArr) {
            fnArr = new Array();
            this.__propertyChangeFnObj[key] = fnArr;
        }
        fnArr.push(funobj);
    },
    /**
     * 明细字段值变化绑定事件，绑定后对新添加的行也生效
     * @params fieldMark(String) 绑定的明细字段标示串，不带下划线标示
     */
    bindDetailFieldChangeEvent: function (fieldMarkStr, funobj) {
        const reg = /^field\d+$/;
        !!fieldMarkStr && fieldMarkStr.split(",").map(key => {
            if (!key || !reg.test(key))
                return "";
            let fnArr = this.__detailFieldChangeFnObj[key];
            if (!!!fnArr) {
                fnArr = new Array();
                this.__detailFieldChangeFnObj[key] = fnArr;
            }
            fnArr.push(funobj);
        });
    },
    /**
     * 刷新当前卡片页面
     */
    reloadCard: function (params = {}) {
        this.getCurrentModeStore().reloadCard(params);
    },
    /**
     * 卡片保存方法 doCardSubmit(pageexpandid, issystemflag, btntype,isRefreshto,callBack)
     * @param pageexpandid string,页面扩展id,必填
     * @param issystemflag string ,是否是系统默认，默认值 0 选填
     * @param btntype string,按钮类型，选填，默认值为 空 ；3 //保存并新建4 //保存并复制5 //明细导入 99保存草稿
     * @param isRefreshto boolean,默认值true,保存后是否跳转到显示页面，默认值true，选填
     * @param callBack function,保存完成后回调方法，选填
     * @param method submit接口的src替换参数
     */
    doCardSubmit: function (pageexpandid, issystemflag = '0', btntype = "", isRefreshto = true, callBack = () => { },method?:string) {
        this.getCurrentModeStore().Actions.doSubmit(pageexpandid, issystemflag, btntype, isRefreshto, callBack,method);
    },
    /**
    * @param pageexpandid   获取页面扩展id
    */
    getCardSubmitExpendId: function () {
        const rightmenus = toJS(this.getCurrentModeStore().cardTab.rightMenus);
        let expendid: string = "";
        _.forEach(rightmenus, (item: any) => {
            if (item.function.indexOf("doSubmit") > -1) {
                expendid = item.key;
            }
        })
        return expendid;
    },
    //根据href获取值
    getHrefQuery: function (href: string) {
        const query = href.split('?')[1];
        const querys = query ? query.split("&") : [];
        const queryObj: any = {};
        querys.map(q => {
            const index = q.indexOf("=");
            const name = q.substring(0, index);
            const value = q.substring(index + 1);
            _.set(queryObj, name, value);
        });
        return queryObj;
    },
    //列表滑动打开卡片，关闭滑动的窗口
    closePageBySlide: function () {
        formModeStores.Search.slideModalVisible = false;
    },
    /**加下公共的全局的方法 */
    ...modeForm_pc,
    /**
    * 钩子机制，指定动作触发注册函数
    */
    ACTION_ADDROW: "action_addrow_",
    ACTION_DELROW: "action_delrow_",
    actionFnList: {},
    registerAction: function (key, fn) {
        if (typeof (fn) !== "function")
            return;
        if (!(key in this.actionFnList) || !(this.actionFnList[key] instanceof Array))
            this.actionFnList[key] = new Array();
        this.actionFnList[key].push(fn);
    },
    triggerAction: function (key, args: any = [], timeout = 0) {
        const fnAction = () => {
            if (key.indexOf(this.ACTION_ADDROW) > -1) {
                const detailIndex = parseInt(key.replace(this.ACTION_ADDROW, ""));
                try {
                    eval("_customAddFun" + detailIndex + "(" + args[0] + ")");
                } catch (e) { }
            } else if (key.indexOf(this.ACTION_DELROW) > -1) {
                const detailIndex = parseInt(key.replace(this.ACTION_DELROW, ""));
                try {
                    eval("_customDelFun" + detailIndex + "()");
                } catch (e) { }
            }
            const fnArr = this.actionFnList[key] || [];
            fnArr && fnArr.map(fn => {
                try {
                    fn(...args);
                } catch (e) { }
            });
        }
        timeout > 0 ? window.setTimeout(() => {
            fnAction();
        }, timeout) : fnAction();
    },
    /**
    * 获取选择框字段对应的显示值
    */
    getSelectShowName: function (fieldMark, splitChar) {
        try {
            if (fieldMark.indexOf("field") === -1)
                return "";
            if (typeof splitChar === "undefined" || splitChar === "")
                splitChar = ",";
            let showname = "";

            const fieldValue = this.getFieldValue(fieldMark);
            const info = this.getFieldInfo(fieldMark);
            if (fieldValue !== "" && info.fieldhtmltype == 5 && info.options) {
                const selectitemlist = toJS(info.options) || [];
                let valueArray = fieldValue.split(",");
                valueArray = valueArray.filter(v => v !== "");
                selectitemlist.map(item => {
                    if (item.key !== "" && _.indexOf(valueArray, item.key + "") > -1) {
                        if (showname !== "")
                            showname += splitChar;
                        showname += item.showname;
                    }
                });
            }
            return showname;
        } catch (error) {

        }
    },
    /**
     * 控制radio框字段打印时仅打印选中值名称
     */
    controlRadioPrintText: function (fieldMark) {
        try {
            this.getCurrentModeStore().batchControlVariableMap({ [`radioPrintText_${fieldMark}`]: true });
        } catch (error) {

        }
    },
    //根据行号获取行序号
    getDetailRowSerailNum: function (mark, rowIndex = -1) {
        try {
            let detailMark = "";
            let serialNum = -1;
            if (mark.startsWith("field") && mark.indexOf("_") > -1) {
                const [fieldid, index] = mark.split("_");
                let fieldProps = this.getFieldInfo(fieldid);
                const detailindex = fieldProps["detail"];
                detailMark = detailindex;
                rowIndex = index;
            } else if (mark.startsWith("detail_")) {
                detailMark = mark;
            }
            const keyArr = this.getCurrentModeStore().cubeForm.$(detailMark).map(d => d.key);
            const rowI = keyArr.indexOf(Number(rowIndex));
            if (rowI > -1) {
                serialNum = rowI + 1;
            }
            return serialNum;
        } catch (error) {

        }
    },
    //获取明细行总数
    getDetailRowCount: function (detailMark) {
        try {
            const allRowIndexStr = this.getCurrentModeStore().cubeForm.$(detailMark).map(d => d.key);
            return allRowIndexStr === "" ? 0 : allRowIndexStr.length;
        } catch (error) {

        }
    },
    /**
    * 控制明细数据行的显示及隐藏
    * @param detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
    * @param rowIndexMark(String) 明细行标示，全部行:all,部分行："1，2，3"
    * @param needHide 是否隐藏行，true:隐藏，false:显示
    */
    controlDetailRowDisplay: function (detailMark, rowIndexMark, needHide = true) {
        try {
            if (rowIndexMark === "all")
                rowIndexMark = this.getDetailAllRowIndexStr(detailMark);
            let attr: any = {};
            rowIndexMark !== "" && rowIndexMark.split(",").map(rowIndex => {
                attr[`row_${rowIndex}`] = { needHide };
            });
            const from = this.getCurrentModeStore().cubeForm;
            if (!from.has(detailMark)) {
                if (window.console) console.log(` ${detailMark} Not Exist`);
                return null;
            }
            this.getCurrentModeStore().controlDetailRowAttr(detailMark, attr);
        } catch (error) {

        }
    },
    /**
     * 控制明细数据行check是否禁用勾选
     * @param detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
     * @param rowIndexMark(String) 明细行标示，全部行:all,部分行："1，2，3"
     * @param disableCheck 是否禁用勾选
     */
    controlDetailRowDisableCheck: function (detailMark, rowIndexMark, disableCheck = true) {
        if (rowIndexMark === "all")
            rowIndexMark = this.getDetailAllRowIndexStr(detailMark);
        let attr = {};
        rowIndexMark !== "" && rowIndexMark.split(",").map(rowIndex => {
            attr[`row_${rowIndex}`] = { disableCheck };
        });
        this.getCurrentModeStore().controlDetailRowAttr(detailMark, attr);
    },
    //获取明细选中行主键ID
    getDetailCheckedRowKey: function (detailMark) {
        try {
            const allDetailVals = this.getCurrentModeStore().cubeForm.$(detailMark).values().map(d => d);
            const allRowKeyArr: any = [];
            _.forEach(allDetailVals, (item: any, index) => {
                if (item.checkbox == "1") {
                    allRowKeyArr.push(item['dtl_id']);
                }
            });
            return `${allRowKeyArr}`;
        } catch (error) {

        }
    },
    //获取明细选中行下标，逗号分隔
    getDetailCheckedRowIndexStr: function (detailMark) {
        try {
            const checkbox = this.getCurrentModeStore().cubeForm.$(detailMark).values().map(d => d.checkbox);
            const detailIndex = this.getCurrentModeStore().cubeForm.$(detailMark).map(d => d.key);
            const checkIndex: any = [];
            _.forEach(checkbox, (item: string, index) => {
                if (item == "1") {
                    checkIndex.push(detailIndex[index]);
                }
            });
            return `${checkIndex}`;
        } catch (error) {

        }
    },
    /**
    * @param type {onblur、onfocus、onclick、ondbclick、mouseover、mouseout}
    * 字段绑定公式触发动作事件
    */
    bindFieldAction: function (type, fieldids, fn) {
        try {
            if (typeof (fn) !== "function")
                return;
            const reg = /^field[-]?\d+$/;//[-]? 匹配 ecme下字段为负
            const fieldArr = fieldids.split(",");
            fieldArr && fieldArr.map(fieldKey => {
                if (reg.test(fieldKey)) {
                    this.registerAction(`${fieldKey}|${type}`, fn);
                }
            });
        } catch (error) {

        }
    },
    triggerFieldAction: function (type, fieldMark) {
        if (!fieldMark || fieldMark.indexOf("field") !== 0)
            return;
        const index = fieldMark.indexOf("_");
        const fieldKey = index > 0 ? fieldMark.substring(0, index) : fieldMark;
        const rowIndex = index > 0 ? parseInt(fieldMark.substring(index + 1)) : -1;
        this.triggerAction(`${fieldKey}|${type}`, [fieldKey, rowIndex]);
    },
    /**
    * 建模操作注册接口
    */
    OPER_ADDROW: 'oper_addrow', //添加明细行
    OPER_DELROW: 'oper_delrow', //删除明细行
    eventList: {},
    registerCheckEvent: function (types, fn) {
        if (typeof (fn) !== "function")
            return;
        const arr = types.split(",");
        arr && arr.map(t => {
            if (!(t in this.eventList))
                this.eventList[t] = new Array();
            this.eventList[t].push(fn);
        })
    },
    /**
     * 字段组件自定义渲染
     * 单行文本类型，支持代理渲染原字段组件
     * 所有表单字段，支持换行追加组件
     */
    proxyComps: {},
    afterComps: {},
    proxyFieldComp: function (fieldMark, el, range) {
        this.customFieldComp(fieldMark, el, range, 1);
    },
    afterFieldComp: function (fieldMark, el, range) {
        this.customFieldComp(fieldMark, el, range, 2);
    },
    customFieldComp: function (fieldMark, el, range, type) {
        if (!fieldMark || fieldMark.indexOf("field") !== 0)
            return;
        const fieldid = fieldMark.split("_")[0];
        const comp = typeof el === "string" ? React.createElement("div", { dangerouslySetInnerHTML: { __html: el } }) : el;
        const rangeArr = !!range ? range.split(",") : ["1", "2", "3"];
        if (type === 1) {
            const fieldAttr = this.getFieldInfo(fieldid);
            if (fieldAttr.fieldhtmltype == 1 && fieldAttr.fieldtype == 1) { //单行文本 字段类型
                this.proxyComps[fieldMark] = { comp, rangeArr };
                this.forceRenderField(fieldMark);
            }
        } else if (type === 2) {
            this.afterComps[fieldMark] = { comp, rangeArr };
            this.forceRenderField(fieldMark);
        }
    },
    forceRenderField: function (fieldMark) {
        const that = this;
        try {
            const [fieldid, index] = fieldMark.split("_");
            let fieldProps = that.getFieldInfo(fieldid);
            if (fieldProps.isdetail) {
                const detailindex = fieldProps["detail"];
                this.getCurrentModeStore().cubeForm.$(detailindex).$(index).$(fieldid).forceRender = new Date().getTime();
            } else {
                this.getCurrentModeStore().cubeForm.$(fieldMark).forceRender = new Date().getTime();
            }
        } catch (e) {

        }
    },
    renderCustomComp: function (fieldMark, viewAttr, type, extendProps = {}) {
        const customComps = type === 1 ? this.proxyComps : this.afterComps;
        if (fieldMark in customComps) {
            const customComp = customComps[fieldMark];
            const { comp, rangeArr } = customComp;
            if (_.indexOf(rangeArr, viewAttr.toString()) > -1) {
                return type === 1 ? React.cloneElement(comp, { ...extendProps }) : comp;
            }
        }
        return null;
    },
    /**
     * 代理组件渲染函数
     */
    proxyCompFn: {},
    proxyFieldContentComp: function (fieldMark, fn) {
        if (typeof fn === "function")
            this.proxyCompFn[`FieldContent_${fieldMark}`] = fn;
    },
    getCustomProxyCompFn: function (key) {
        return key in this.proxyCompFn ? this.proxyCompFn[key] : null;
    },
    /**
     * 控制日期选择范围
     */
    controlDateRange: function (fieldMark, start, end) {
        try {
            let startDate = '';
            let endDate = '';
            const reg = /^(-?\d+)(\.\d+)?$/;
            if (typeof start !== "undefined") {
                startDate = start.toString();
                if (reg.test(startDate))
                startDate = new Date(new Date().getTime() + start * 24 * 60 * 60 * 1000).toLocaleDateString().replace(/日/g, '').replace(/\/|年|月/g, '-').replace(/[^\d-]/g,'');    
            }
            if (typeof end !== "undefined") {
                endDate = end.toString();
                if (reg.test(endDate))
                endDate = new Date(new Date().getTime() + end * 24 * 60 * 60 * 1000).toLocaleDateString().replace(/日/g, '').replace(/\/|年|月/g, '-').replace(/[^\d-]/g,'');
            }
            const [fieldid, index] = fieldMark.split("_");
            let fieldProps = this.getFieldInfo(fieldid);
            if (fieldProps.isdetail) {
                const detailindex = fieldProps["detail"];
                this.getCurrentModeStore().cubeForm.setDate(`${detailindex}.${index}.${fieldid}`, startDate, endDate);
            } else {
                this.getCurrentModeStore().cubeForm.setDate(fieldMark, startDate, endDate);
            }
        } catch (error) {

        }
    },
    /**
     * ecmeField绑定事件回调 event (onChange  onblur onfocus)三种事件触发回调
     */
    ecmeFieldEventCallBack: function (type, fieldMark, comfrom) {
        if (!fieldMark || fieldMark.indexOf("field") !== 0)
            return;
        const index = fieldMark.indexOf("_");
        const rowIndex = index > 0 ? parseInt(fieldMark.substring(index + 1)) : -1;
        if (fieldMark.startsWith('field-') &&  this.getCurrentModeStore() ) {
            const newvalue = this.getFieldValue(fieldMark);
            const fieldInfo = this.getFieldInfo(fieldMark);
            let _fieldhtmltype = fieldInfo.fieldhtmltype;
            if (comfrom == 'form' && _fieldhtmltype == 1) {
                return;
            }
            let browserShowName = "";
            if(_fieldhtmltype == 3){
                browserShowName = this.getBrowserShowName(fieldMark);
            }
            let fieldid;
            if (rowIndex > -1) {
                fieldid = fieldMark.substring(0, index)
            } else {
                fieldid = fieldMark;
            }
            let _type = `${type}`;
            const ecmeFieldEventCallBack = this.getCurrentModeStore().cubeForm.card.ecmeFieldEventCallBack;
            let iscustom = fieldInfo.issystem === "4" ? "true":"false";
            if (typeof (ecmeFieldEventCallBack) == 'function') {
                try {
                    const params = { 
                        changetype: _type,//event (onChange  onblur onfocus)
                        fieldMark: fieldid,//field-123
                        fieldInfo: fieldInfo,//字段基本信息（包括fiedhtmltype == ）
                        fieldnewvalue: newvalue,//字段新值
                        rowIndex: rowIndex, //主表 -1 明细：行id
                        iscustom: iscustom, //是否为自定义字段  ture：是 false：否
                        browserShowName: browserShowName,//浏览按钮显示名称
                    };
                    this.getCurrentModeStore().cubeForm.card.ecmeFieldEventCallBack(params);
                } catch (e) {
                    console.log(e);
                }
            }
        }
    },
    /***
     * 根据字段标识获取字段组件
     */
    generateFieldContentComp: function (fieldMark) {
        try {
            const index = fieldMark.indexOf("_");
            const fieldId = fieldMark.split("_")[0];
            const fieldid = index > -1 ? fieldMark.substring(5, index) : fieldMark.substring(5);
            const rowIndex = index > -1 ? fieldMark.substring(index + 1) : -1;
            const fieldInfo = this.getFieldInfo(fieldId);
            const isdetail = fieldInfo.isdetail;
            const detail = fieldInfo.detail;
            const card = this.getCurrentModeStore();
            if (isdetail) {
                const excel: any = card.modeExcel.getExcel(detail);
                const cell = excel.cells.slice().filter(d => d.field == fieldid && d.etype == '3') || [];
                return cell && cell.length > 0 ? <TableCell
                    cell={cell[0]}
                    form={card.cubeForm.$(detail).$(rowIndex)}
                    excel={excel}
                    card={card}
                    index={rowIndex}
                    detail={detail}
                /> : <span></span>
            } else {
                const excel: any = card.modeExcel.cells.slice().filter(d => d.field == fieldid && d.etype == '3') || [];
                return excel && excel.length > 0 ? <TableCell
                    cell={excel[0]}
                    form={card.cubeForm}
                    excel={card.modeExcel}
                    card={card}
                    index={rowIndex}
                /> : <span></span>
            }
        } catch (error) {
            return <span>Field Not Exist</span>;
        }
    },
    /***调用右键事件
     * 系统按钮：type= functionname
     * 页面扩展 type = doCustomFunction,expendid,name,必填一个，先走前面的id
     */
    doRightBtnEvent: function(type,expendid?,name?){
        try{
            const card = this.getCurrentModeStore();
            const rightMenu = toJS(card.cardTab.rightMenus);
            let btnObj  = type;
            let pageid ;
            if(type === 'doCustomFunction'){ //自定义按钮
                if(expendid){
                    pageid = expendid;
                }else if(name){  //支持多语言。eg：商务管理~~Business~~商務管理
                    const names = name.split('~~');
                    rightMenu && rightMenu.map(item =>{
                        if(_.indexOf(names, item.name) >= 0){
                            btnObj = item; 
                            pageid = item.key;
                        }
                    });
                }else{
                    this.showMessage('请填写指定的页面扩展id或者名称！');
                }
            }else{
                rightMenu && rightMenu.map(item =>{
                    let _fun = item.function.replace('javascript:', '');
                    _fun = _fun.split("(")[0];
                    if(type === _fun){
                        btnObj = item; 
                        pageid = item.key;
                    }
                });
            }
            if(btnObj && pageid){
                card.cardTab.rightMenuHandle(pageid)
            }
        }catch(e){
        }
    },
    /***
     * 打开侧滑窗口
     */
    slideOpenModal:function(bool,url,sliderPercentage = 70){
        this.getCurrentModeStore().showSlideModal(bool, url, sliderPercentage);
    },

    /***
     * 控制全局spin的开始与结束
     */
    showLoading:function(bool,size?,tip?){
        this.getCurrentModeStore().showGlobalSpin = {
            isShow: bool ? 'show' : 'hide',
            size: size || 'defalut',
            tip: tip || '',
        }
    },
    /*****
     * 表单提交之前添加参数
     */
    appendSubmitParam: function(obj={}){
        _.forIn(obj, (v,k) =>{
            if(_.indexOf(importantParamRange, k) > -1)
                delete obj[k];
        });
        this.getCurrentModeStore().changeSubmitParam(obj);
    }
}


export interface MyCustomDialogProps {
    prop: object,
    buttons: any[]
}
@observer
export class MyCustomDialog extends React.Component<MyCustomDialogProps, any>{
    constructor(props) {
        super(props);
        const { prop, buttons } = this.props;
        this.state = { visible: true, prop: prop, buttons: buttons };
    }
    render() {
        const { prop, buttons } = this.state;
        return (
            <div id="dialogdiv">
                <WeaDialog
                    className={`${prop.title ? "":'cube-dialog-notitle'} wea-auth-modal cube-dialog`}
                    iconBgcolor={"#96358a"}
                    icon={'icon-coms-ModelingEngine'}
                    iconFontColor={"#fff"}
                    buttons={buttons}
                    visible={this.state.visible}
                    hasScroll={true}
                    destroyBodyOnClose={true}
                    onCancel={() => { this.setState({ visible: false }); }}
                    {...prop}
                >
                </WeaDialog >
            </div>
        )
    }

    close = (callBack) => {
        this.setState({ visible: false });
        callBack&&typeof callBack == 'function' && callBack();
    }

    show = () => {
        this.setState({ visible: true });
    }

    update = (prop, buttons) => {
        this.setState({ prop: prop, buttons: buttons });
    }
}

//锁定列情况，加载完同步一次高度宽度
export const syncLockedForDidMount = (groupid) => {
    const syncFn = () =>{
        const dTableArea = jQuery("#dTableArea_"+groupid);
        // if(dTableArea.attr("data-supportlockedcol") !== "true")
        //     return;
        const oTable = dTableArea.find("table#oTable"+groupid);
        const oTable_head = dTableArea.find("table#oTable"+groupid+"_head");
        const oTableLocked = dTableArea.find("table#oTable"+groupid+"_locked");
        const oTableLocked_head = dTableArea.find("table#oTable"+groupid+"_head_locked");
        if(oTable.length !== 1 || oTableLocked.length !== 1)
            return;
        oTableLocked.find("tr[data-rowindex]").each(function(){
            const rowindex = jQuery(this).attr("data-rowindex");
            const lockedRow = oTableLocked.find("tr[data-rowindex="+rowindex+"]");
            const dataRow = oTable.find("tr[data-rowindex="+rowindex+"]");
            if(lockedRow.length === 1 && dataRow.length === 1){
                if(dataRow.height()==lockedRow.height()){
                    return true;
                }
                const maxHeight = dataRow.height() >= lockedRow.height() ? dataRow.height() : lockedRow.height();
                lockedRow.add(dataRow).css("height", maxHeight);
                oTable_head.add(oTableLocked_head).find("tr[data-rowindex="+rowindex+"]").css("height", maxHeight);
            }
        });
        // //解决隐藏列宽度变化问题,将数据层的隐藏列宽度总和赋值给锁定层
        // const lockedCount = oTableLocked.find(".detailControlWidth").children().length;
        // let totalWidth = 0;
        // oTable.find(".detailControlWidth").children().each(function(index){
        //     if(index < lockedCount && !jQuery(this).hasClass("detail_hide_col"))
        //         totalWidth += jQuery(this).width();
        // });
        // if(Math.abs(oTableLocked.width()-totalWidth) > 3){
        //     dTableArea.find("table#oTable"+groupid+"_head_locked").width(totalWidth);
        //     oTableLocked.width(totalWidth);
        // }
    }
    const begintime = new Date().getTime();
    const didsynctimer = window.setInterval(()=>{
        try{
            syncFn();
            const curtime = new Date().getTime(); 
            if(curtime - begintime > 2000)
                window.clearInterval(didsynctimer);
        }catch(e){}
    }, 0);
}
